<template>
  <div class="conversation-friends">
    <!-- tab -->
    <div class="friends-title">
      <span
        class="tab can-not-select"
        :class="{ 'tab-chose': currentTab === 'LastChat' }"
        @click="setTab('LastChat')"
        >会话</span
      >
      <span
        class="tab can-not-select"
        :class="{ 'tab-chose': currentTab === 'AddressList' }"
        @click="setTab('AddressList')"
        >通讯录</span
      >
      <span
        class="tab can-not-select"
        :class="{ 'tab-chose': currentTab === 'ChatRoom' }"
        @click="setTab('ChatRoom')"
        >群聊</span
      >
    </div>

    <!-- 搜索 -->
    <div class="search-box">
      <el-input
        class="search-input"
        prefix-icon="el-icon-search"
        type="text"
        placeholder="请输入内容"
        maxlength="20"
        show-word-limit
        v-model="searchInfo"
        @keyup.enter.native="searchChange"
      ></el-input>
    </div>

    <!-- 会话列表 | 好友列表 | 群聊列表 -->
    <div class="friends-content scroll">
      <!-- 会话|通讯录|群聊|搜索结果 -->
      <div
        class="friend-info"
        :class="{
          selected:
            currentTab === 'AddressList'
              ? currentChose === message.FriendId
              : currentChose === message.UserName,
        }"
        v-for="(message, index) in currentInfo[currentPage]"
        :key="index"
        @click="choseFriend(message)"
      >
        <!-- 头像和提示 -->
        <div class="avatar-tip">
          <!-- 头像 -->
          <img class="img" :src="getAvatar(message)" :alt="'好友头像'" />
          <!-- 未读消息数 -->
          <div
            v-if="
              currentTab === 'LastChat' &&
              message.UnreadCnt &&
              message.UnreadCnt > 0
            "
            class="tip"
            v-text="message.UnreadCnt < 99 ? message.UnreadCnt : '...'"
            :title="message.UnreadCnt"
          ></div>
        </div>
        <!-- 昵称和消息内容 -->
        <div class="nick-content">
          <!-- 昵称 -->
          <div class="friend-nick ellipsis" v-text="getNickName(message)"></div>
          <!-- 消息内容 -->
          <div
            v-if="currentTab === 'LastChat'"
            class="chat-content ellipsis"
            v-text="
              message.Digest
                ? message.UserName.indexOf('@chatroom') >= 0
                  ? message.IsSend
                    ? message.Digest
                    : message.Digest.replace('%s:', '')
                  : message.Digest
                : ''
            "
          ></div>
        </div>
        <!-- 时间和刷新 -->
        <div class="time-disturb">
          <div
            v-if="currentTab === 'LastChat'"
            v-text="$options.filters.transformTime(message.UpdateTime)"
          ></div>
          <div class="opration-btns">
            <i
              v-if="message.UserName !== 'notifymessage'"
              class="fa fa-retweet sigle-fresh"
              aria-hidden="true"
              @click.stop="getFriendDetail(message)"
            ></i>
            <i
              v-if="currentTab === 'AddressList'"
              class="el-icon-delete sigle-fresh"
              @click.stop="deleteChat(message)"
            ></i>
          </div>
        </div>
      </div>
      <template v-if="currentInfo.length === 0 && currentTab === 'Search'">
        <div class="current-info-null">搜索不到结果！</div>
      </template>
    </div>

    <!-- 分页、刷新等按钮 -->
    <div class="friends-bottom">
      <!-- 好友数 -->
      <el-tooltip
        effect="dark"
        :content="currentTitle[currentTab]"
        placement="top-start"
      >
        <el-button type="text" v-text="counts"></el-button>
      </el-tooltip>
      <!-- 上一页 -->
      <el-tooltip effect="dark" content="上一页" placement="top-start">
        <el-button
          type="text"
          icon="el-icon-arrow-left"
          :disabled="currentPage === 0"
          @click="changePage(-1)"
        ></el-button>
      </el-tooltip>
      <!-- 当前页 -->
      <el-tooltip effect="dark" content="当前页" placement="top-start">
        <el-button type="text" v-text="currentPage + 1"></el-button>
      </el-tooltip>
      <!-- 分割线 -->
      <el-divider direction="vertical"></el-divider>
      <!-- 总页书 -->
      <el-tooltip effect="dark" content="总页数" placement="top-start">
        <el-button type="text" v-text="maxPage"></el-button>
      </el-tooltip>
      <!-- 下一页 -->
      <el-tooltip effect="dark" content="下一页" placement="top-start">
        <el-button
          type="text"
          icon="el-icon-arrow-right"
          :disabled="currentPage + 1 === maxPage"
          @click="changePage(1)"
        ></el-button>
      </el-tooltip>
      <!-- 刷新 -->
      <el-tooltip
        effect="dark"
        :content="freshTitle[currentTab]"
        placement="top-start"
      >
        <el-button
          style="color: #fff"
          type="text"
          icon="el-icon-refresh"
          :loading="freshDisabled"
          @click="fresh(currentTab)"
        ></el-button>
      </el-tooltip>
      <!-- 清空 -->
      <el-tooltip
        effect="dark"
        :content="deleteTitle[currentTab]"
        placement="top-start"
      >
        <el-button
          style="color: red"
          type="text"
          icon="el-icon-delete"
          @click="removeData(currentTab)"
        ></el-button>
      </el-tooltip>
    </div>
  </div>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'
export default {
  data() {
    return {
      // 总数的title
      currentTitle: {
        LastChat: '会话数量',
        AddressList: '好友数量',
        ChatRoom: '群聊数量',
      },
      // 刷新的title
      freshTitle: {
        LastChat: '刷新会话列表',
        AddressList: '刷新好友列表',
        ChatRoom: '刷新群聊列表',
      },
      // 删除的title
      deleteTitle: {
        LastChat: '清空会话列表',
        AddressList: '清空好友列表',
        ChatRoom: '清空群聊列表和陌生人列表',
      },
      //   currentChose: '', // 当前的选择
      searchInfo: '', // 搜索内容
      searchResult: [], // 搜索结果
      showRight: false, // 右键弹框
      chatToDel: {} // 右键选择的message
    }
  },
  computed: {
    ...mapGetters({
      friends: 'nedb/friends', // 当前的通讯录列表
      friendsAll: 'nedb/friendsAll', // 当前的通讯录列表
      chatRooms: 'nedb/chatRooms', // 当前的群聊列表
      chatRoomsAll: 'nedb/chatRoomsAll', // 当前的群聊列表
      conversations: 'nedb/conversations', // 当前的会话列表
      ghMap: 'conversation/ghMap', // 公众号列表
      currentTab: 'conversation/currentTab', // 当前tag回显
      chatRoomPages: 'conversation/chatRoomPages', // 当前页面回显
      currentWechat: 'conversation/currentWechat', // 当前选择的微信
      freshDisabled: 'conversation/freshDisabled', // 刷新按钮不可用
      lastChatPages: 'conversation/lastChatPages', // 当前页面回显
      currentFriends: 'conversation/currentFriends', // 当前页面回显
      currentWeChatId: 'conversation/currentWeChatId', // 当前选择的微信
      addressListPages: 'conversation/addressListPages', // 当前页面回显
    }),
    // 当前微信的公众号列表
    ghList() {
      return this.ghMap[this.currentWeChatId] ? this.ghMap[this.currentWeChatId] : []
    },
    // 当前的信息
    currentInfo() {
      switch (this.currentTab) {
        case 'LastChat':
          return this.conversations
        case 'AddressList':
          return this.friends
        case 'ChatRoom':
          return this.chatRooms
        case 'Search':
          return this.searchResult
        default:
          return []
      }
    },
    // 当前选中的好友的id
    currentChose() {
      if (this.currentFriends[this.currentWeChatId]) {
        return this.currentFriends[this.currentWeChatId].FriendId || this.currentFriends[this.currentWeChatId].UserName
      }
      return ''
    },
    // 当前的信息
    currentPage() {
      switch (this.currentTab) {
        case 'LastChat':
          return this.lastChatPages[this.currentWeChatId] || 0
        case 'AddressList':
          return this.addressListPages[this.currentWeChatId] || 0
        case 'ChatRoom':
          return this.chatRoomPages[this.currentWeChatId] || 0
        default:
          return 0
      }
    },
    // 消息数量|好友数量|群聊数量
    counts() {
      let count = 0
      if (typeof (this.currentInfo) === 'object') {
        for (const iterator of this.currentInfo) {
          count += iterator.length
        }
      }
      return count
    },
    // 最大页数
    maxPage() {
      if (typeof (this.currentInfo) === 'object') {
        if (this.currentInfo.length === 0) {
          return 1
        }
        return this.currentInfo.length
      }
      return 1
    },
    // conversation 对应的好友的信息
    conversMap() {
      let cmp = {}
      if (this.friends.length > 0) {
        for (const friends of this.friends) {
          for (const friend of friends) {
            cmp[friend.FriendId] = friend
          }
        }
      }
      if (this.chatRooms.length > 0) {
        for (const rooms of this.chatRooms) {
          for (const room of rooms) {
            cmp[room.UserName] = room
          }
        }
      }
      return cmp
    },
  },
  watch: {
    searchInfo(val) {
      this.debounceInput()
    }
  },
  created() {
    // 节流 几秒只执行一次
    // this.fresh = this._.throttle(this.fresh, 3000)
    this.getFriendDetail = this._.throttle(this.getFriendDetail, 2000)
    // 防抖
    this.debounceInput = this._.debounce(this.debounceInput, 500)
  },
  methods: {
    debounceInput() {
      if (this.searchInfo) {
        let result = []
        for (const friend of this.friendsAll) {
          if (friend.FriendNick && friend.FriendNick.indexOf(this.searchInfo) >= 0) {
            result.push(friend)
          } else if (friend.Memo && friend.Memo.indexOf(this.searchInfo) >= 0) {
            result.push(friend)
          } else if (friend.Phone && friend.Phone.indexOf(this.searchInfo) >= 0) {
            result.push(friend)
          }
        }
        for (const chatRoom of this.chatRoomsAll) {
          if (chatRoom.NickName && chatRoom.NickName.indexOf(this.searchInfo) >= 0) {
            result.push(chatRoom)
          } else if (chatRoom.Remark && chatRoom.Remark.indexOf(this.searchInfo) >= 0) {
            result.push(chatRoom)
          }
        }
        if (result.length === 0) {
          this.searchResult = []
        } else {
          for (let i = 0; i < result.length; i += 50) {
            this.searchResult.push(result.slice(i, i + 50))
          }
        }
        this.$store.commit('conversation/SET_CURRENT_TAB', 'Search')
      } else {
        this.searchResult = []
        this.$store.commit('conversation/SET_CURRENT_TAB', 'LastChat')
      }
    },
    // 计算好友昵称
    getNickName(message) {
      if (message.UserName === 'notifymessage') {
        return '服务通知'
      }
      let friendId = message.FriendId || message.UserName
      if (this.conversMap[friendId]) {
        // 如果是个人：优先展示Memo 如果没有Memo展示FriendNick
        if (friendId.indexOf('@chatroom') === -1) {
          return this.conversMap[friendId].Memo || this.conversMap[friendId].FriendNick
        } else {
          // 如果是群聊: 优先展示Remark NickName
          return this.conversMap[friendId].Remark || this.conversMap[friendId].NickName
        }
      }
      for (const gh of this.ghList) {
        if (gh.Username === message.UserName) {
          return gh.Nickname || gh.Alias
        }
      }
      return friendId
    },
    // 获取好友头像
    getAvatar(message) {
      if (message.UserName === 'notifymessage') {
        return require('assets/svg/conversation-notify-message.svg')
      }
      let friendId = message.FriendId || message.UserName
      if (this.conversMap[friendId] && this.conversMap[friendId].Avatar) {
        return this.conversMap[friendId].Avatar
      }
      for (const gh of this.ghList) {
        if (gh.Username === message.UserName) {
          return gh.Avatar || gh.Icon
        }
      }
      return require('assets/svg/conversation-image-error.svg')
    },
    // 切换tab
    setTab(tab) {
      // 如果已经是这个tag 不做处理
      if (tab === this.currentTab) return
      this.searchInfo = ''
      this.$store.commit('conversation/SET_CURRENT_TAB', tab)
    },
    // 刷新
    fresh(currentTab) {
      if (this.currentWeChatId) {
        this.$store.commit('conversation/SET_FRESH_DISABLED', true)
        switch (currentTab) {
          case 'LastChat':
            this.$store.dispatch('websocket/TriggerConversationPushTask')
            setTimeout(() => {
              // if (this.freshDisabled) {
              this.$store.commit('conversation/SET_FRESH_DISABLED', false)
              // }
            }, 3000);
            break
          case 'AddressList':
            this.removeData('AddressList')
            this.$store.dispatch('websocket/TriggerFriendPushTask')
            break
          default:
            this.$store.dispatch('nedb/RemoveAllRoomByWechatId', this.currentWechat.WeChatId)
            this.$store.dispatch('websocket/TriggerChatroomPushTask', this.currentWeChatId)
            break
        }
      } else {
        this.$message({
          message: '请先选中微信',
          type: 'warning'
        })
      }
    },
    // 删除会话|好友|群
    deleteChat(chatToDel) {
      switch (this.currentTab) {
        case 'LastChat':
          this.$message({
            type: 'info',
            message: '从本地删除本地会话，待实现！',
            duration: 1000
          })
          break
        case 'AddressList':
          this.$confirm('此操作将删除该好友, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$store.dispatch('websocket/DeleteFriendTask', chatToDel)
            this.$message({
              type: 'info',
              message: '正在删除!'
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });
          break
        case 'ChatRoom':
          this.$message({
            type: 'info',
            message: '从本地删除群聊，待实现！',
            duration: 1000
          })
          break
        default:
          break
      }
    },
    // 清除本地数据
    removeData(currentTab) {
      if (this.currentWeChatId) {
        switch (currentTab) {
          case 'LastChat':
            this.$store.dispatch('nedb/RemoveAllConversationsByWechatId', this.currentWechat.WeChatId)
            break
          case 'AddressList':
            this.$store.dispatch('nedb/RemoveAllFriensByWechatId', this.currentWechat.WeChatId)
            break
          case 'ChatRoom':
            this.$store.dispatch('nedb/RemoveAllRoomByWechatId', this.currentWechat.WeChatId)
            this.$store.dispatch('nedb/RemoveMembersByWechatId', this.currentWechat.WeChatId)
            break
          default:
            break
        }
      } else {
        this.$message({
          message: '请先选中微信',
          type: 'warning'
        })
      }
    },
    // 页面加减
    changePage(page) {
      let p = this.currentPage + page
      if (p >= 0 && p < this.maxPage) {
        let msg = {
          wechatId: this.currentWeChatId,
          page: p
        }
        switch (this.currentTab) {
          case 'LastChat':
            this.$store.commit('conversation/SET_LAST_CHAT_PAGES', msg)
            break
          case 'AddressList':
            this.$store.commit('conversation/SET_ADDRESS_LIST_PAGES', msg)
            break
          case 'ChatRoom':
            this.$store.commit('conversation/SET_CHAT_ROOM_PAGES', msg)
            break
          default:
            break
        }
      }
    },
    // 获取指定好友的详情
    getFriendDetail(message) {
      let msg = {
        wechatId: this.currentWeChatId,
        friendId: message.UserName || message.FriendId,
      }
      if (msg.friendId.indexOf('@chatroom') > 0) {
        // 判断你是否还在群里
        let memberList = []
        if (message.MemberList) {
          memberList = message.MemberList
        } else if (this.conversMap[msg.friendId]) {
          memberList = this.conversMap[msg.friendId].MemberList
        }
        if (memberList.length > 0 && memberList.indexOf(this.currentWeChatId) < 0) {
          this.$message.warning('你已经不在群里，无法获取群详细信息！')
        } else {
          this.$store.dispatch('websocket/RequestChatRoomInfoTask', msg)
          this.$message.info('指令已经下发！')
        }
      } else {
        this.$store.dispatch('websocket/RequestContactsInfoTask', msg)
        this.$message.info('指令已经下发！')
      }
    },
    // 选择好友或会话
    choseFriend(message) {
      let friend = {}
      let friendId = message.FriendId || message.UserName
      if (this.currentTab === 'LastChat') {
        // 设置当前会话对应的好友信息
        if (message.UserName === 'notifymessage') {
          // 服务通知
          friend = {
            Avatar: require('assets/svg/conversation-notify-message.svg'),
            NickName: '服务通知',
            FriendId: message.UserName,
            WeChatId: message.WeChatId || this.currentWeChatId
          }
        } else if (this.conversMap[friendId]) {
          // 群聊或好友或公众号
          friend = this.conversMap[friendId]
        } else {
          // 看下是不是公众号
          for (const gh of this.ghList) {
            if (gh.Username === message.UserName) {
              for (const key in gh) {
                if (gh.hasOwnProperty(key)) {
                  friend[key] = gh[key]
                }
              }
              if (!gh.Avatar) {
                friend.Avatar = gh.Icon
              }
              friend.WeChatId = this.currentWeChatId
              friend.NickName = gh.Nickname
              friend.FriendId = message.UserName
              friend.isGh = true
              break
            }
          }
        }
        // 如果有未读消息，设置消息已读
        if (message.UnreadCnt && message.UnreadCnt > 0) {
          let readMsg = {
            WeChatId: this.currentWeChatId,
            FriendId: friendId
          }
          // 本地设为已读
          this.$store.dispatch('nedb/SetUnreadCnt', readMsg)
          // 手机上设置消息已读
          this.$store.dispatch('websocket/TriggerMessageReadTask', readMsg)
        }
      } else {
        friend = message
      }

      // 查询最近的消息
      if (JSON.stringify(friend) !== '{}') {
        // 设置coversation页面所选的好友
        let currentFriend = {
          wechatId: this.currentWeChatId,
          friend: friend
        }
        this.$store.commit('conversation/SET_CURRENT_FRIENDS', currentFriend)
        if (message.UpdateTime) {
          friend.UpdateTime = message.UpdateTime
        }
        // 公众号不能获取历史消息
        if (!friend.isGh) {
          this.$store.dispatch('nedb/QueryLastChat', friend)
        }
      } else {
        // 获取好友的详情
        this.getFriendDetail(message)
      }
    },
    // =========================================================================
    // 从服务器获取指定微信的所有聊天
    getHistoryMessageList(wechatId, startTime) {
      if (wechatId === '') return
      let msg = {
        MsgType: 'HistoryMessageList',
        Content: {
          cid: Number(this.currentUser.SupplierId), // 所属客户id  //登录下发下来的supplierid
          wechatid: wechatId,
          startTime: startTime
        }
      }
      this.$websocket.sendSock(msg)
    },
    // 从服务器获取指定微信、指定好友的所有聊天
    queryHistoryMessage(wechatId, friendId, pageSize, pageNo) {
      if (wechatId === '' || friendId === '') return
      let msg = {
        MsgType: 'QueryHistoryMessage',
        Content: {
          cid: Number(this.currentUser.SupplierId), // 所属客户id  //登录下发下来的supplierid
          wechatid: wechatId,
          friendId: friendId,
          pageSize: pageSize >= 1 ? pageSize : 1, // 每页多少条 不能小于1
          pageNo: pageNo >= 1 ? pageNo : 1 // 当前第几页 不能小于1
        }
      }
      this.$websocket.sendSock(msg)
    },

  }
}
</script>

<style lang="scss" scoped>
.conversation-friends {
  width: 270px;
  min-width: 270px;
  margin-right: 5px;
  display: flex;
  flex-direction: column;
  height: 100%;
  overflow: hidden;
  .friends-title,
  .friends-bottom {
    height: 40px;
    min-height: 40px;
    display: flex;
    align-items: center;
    justify-content: space-around;
    color: white;
    // background-color: #545c64;
    background-color: $bg-color-nav-title-2;
  }
  .friends-title {
    .tab {
      width: 90px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      cursor: pointer;
      &:hover {
        background-color: #434a50;
      }
    }
    .tab-chose {
      color: #ffd04b;
      border-bottom: #ffd04b solid 2px;
    }
  }
  .friends-bottom {
    .el-tooltip {
      width: 40px;
      color: white;
    }
    ::v-deep .is-loading {
      border-radius: 0;
    }
  }
  .search-box {
    padding: 5px;
    background-color: $bg-color-content-base;
  }
  .friends-content {
    flex: 1 1 auto;
    display: flex;
    flex-direction: column;
    overflow-y: scroll;
    background-color: $bg-color-content-base;

    .friend-info {
      height: 50px;
      width: 260px;
      overflow: hidden;
      min-height: 50px;
      display: flex;
      cursor: pointer;
      margin-top: 2px;

      .avatar-tip {
        height: 50px;
        width: 50px;
        position: relative;
        .img {
          width: 40px;
          height: 40px;
          margin: 5px;
          font-size: 14px;
        }
        .tip {
          border: solid red 1px;
          width: 20px;
          height: 20px;
          position: absolute;
          top: 0px;
          right: 0px;
          background: red;
          border-radius: 10px;
          color: white;
          text-align: center;
        }
      }

      .nick-content {
        width: 140px;
        display: flex;
        flex-direction: column;
        align-self: center;
        .friend-nick,
        .chat-content {
          max-width: 100%;
          height: 20px;
          line-height: 20px;
        }
      }

      .time-disturb {
        width: 70px;
        min-width: 70px;
        display: flex;
        align-items: center;
        justify-content: space-around;
        flex-direction: column;
        .sigle-fresh:hover {
          color: #41c0fc;
        }
        .opration-btns {
          display: flex;
          justify-content: space-around;
          width: 40px;
          // border: solid red 1px;
        }
      }

      &:hover {
        background-color: #dedcdb;
      }
    }
    .current-info-null {
      text-align: center;
      margin-top: 10px;
    }
    .selected {
      background-color: #c8c6c6;
      &:hover {
        background-color: #c8c6c6;
      }
    }
  }
}
</style>
